//
//  NewCityHomeVC.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/9/13.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import MJRefresh
import SDWebImage
import SVProgressHUD

class NewCityHomeVC: BaseViewController {

    
    lazy var bgView : HomeNavView = {
        
        let temp = Bundle.main.loadNibNamed(self.StringFromClass(classType: HomeNavView.self), owner: nil, options: nil)?.first as! HomeNavView
        
        temp.frame =  CGRect(x: 0, y: 0, width: KScreenW, height: 44)
        
        temp.backgroundColor = UIColor.clear
        
        temp.delegate = self
        
        
        return temp
        
    }()
    
    var haveSrollImage = false
    
    var haveAD = false
    
    var ADModel : HomeOneGroup?

    
    var homeData = [HomeGropModel]()
    
    var latitude = "32.04491"
    
    var longitude = "112.143555"
    
    var adress = "湖北"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.titleView = bgView
        
        weak var weakSelf = self
        LocationManager.sharInstance.getLoction(false) { (location, place, locationMa) in
            
            weakSelf?.latitude = "\(location.coordinate.latitude)"
            
            weakSelf?.longitude = "\(location.coordinate.longitude)"
            
            
            if let temp = place.addressDictionary as NSDictionary?{
                
                
                weakSelf?.adress = temp.object(forKey: "City") as! String
                
                if weakSelf?.adress != nil{
                    
                    weakSelf?.bgView.leftLabel.text = weakSelf?.adress
                    
                }
                
                
                
                
            }
            
            
        }
        
        
        QL1(UserViewModel.shared.key)
        
        
        
        groupTableView.register(UINib(nibName: StringFromClass(classType: HomeTopCell.self), bundle: nil), forCellReuseIdentifier: HomeTopCell.identifer())
        groupTableView.register(UINib(nibName: StringFromClass(classType: NewCityProgramaCell.self), bundle: nil), forCellReuseIdentifier: NewCityProgramaCell.identifer())
        groupTableView.register(UINib(nibName: StringFromClass(classType: HomeFeatureCell.self), bundle: nil), forCellReuseIdentifier: HomeFeatureCell.identifer())

        groupTableView.register(UINib(nibName: StringFromClass(classType: HomeADTableCell.self), bundle: nil), forCellReuseIdentifier: HomeADTableCell.identifer())
        
        
        groupTableView.register(HomeSetionHeader.self, forHeaderFooterViewReuseIdentifier: HomeSetionHeader.identifer())
        
        groupTableView.rowHeight = UITableViewAutomaticDimension
        
        groupTableView.estimatedRowHeight = 100
        
        groupTableView.separatorStyle = .none
        
        
        
        groupTableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf?.loadHomeData()
            
        }
        
        groupTableView.mj_header.beginRefreshing()
        // Do any additional setup after loading the view.
    }
    
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}







extension NewCityHomeVC : HomeNavViewDeleage{
    
    func tittleBtnDidTap() {
        
        let tmepV = SearchController()
        
        
        let nav = BaseNavController(rootViewController: tmepV)
        
        
        present(nav, animated: true, completion: nil)
    }
    
    
    func rightBtnDidTap() {
        
        let temp = UserDefaults.standard.value(forKey: "IsNewCityUser")
        
        if let hehe = temp as? String {
            
            if hehe == "TRUE" {
                UserDefaults.standard.set("FALSE", forKey: "IsNewCityUser")
                
            } else {
                UserDefaults.standard.set("TRUE", forKey: "IsNewCityUser")
                
            }
            
            UIApplication.shared.keyWindow?.rootViewController = TabBarController()
            return
        }
        
        
        UserDefaults.standard.set("TRUE", forKey: "IsNewCityUser")
        
        UIApplication.shared.keyWindow?.rootViewController = TabBarController()
        
        
    }
    
}


extension NewCityHomeVC{
    
    func loadHomeData(){
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=index&a=index", parameters: nil ) {[weak self] (responseObject, error) in
            
            if error == nil {
                
                HomeGloabeModel.golableModel = HomeGloabeModel(dic: responseObject!)
                
                let str0 = HomeGloabeModel.golableModel.app_build
                
                let str1 = Bundle.main.infoDictionary!["CFBundleVersion"] as? String
                
           
                
                
                if str0 != nil && str1 != nil{
                    
                    var number0 = Int(str0!)
                    var number1 = Int(str1!)
                    
                    if number0 == nil || number1 == nil{
                        
                        number0 = 0
                        
                        number1 = 0
                        
                    }
                    
                    if number1! < number0!{
                        
                        HomeGloabeModel.golableModel.ios_tag = "1"
                        
                    }else{
                        
                        HomeGloabeModel.golableModel.ios_tag = "0"
                        
                    }
                    
                }
                
                
                
                self?.homeData = [HomeGropModel]()
                
                for dic in responseObject?["datas"] as! [[String : AnyObject]]{
                    
                    self!.homeData.append(HomeGropModel(dic: dic))
                    
                }
                
//                self?.homeData.remove(at: 0)
                
                
                for item in self!.homeData {
                    if item.type == "1" {
                        
                        self!.haveSrollImage = true
                    }
                    
                    if  item.type == "2"{
                        
                        self!.haveAD = true
                        self?.ADModel = item.item_data
                        
                        
                    }

                }
                
                self!.cachePictures()
                
            }else{
                
                QL1("失败一次")
                
                self!.loadHomeData()
                
                //                self!.groupTableView.mj_header.endRefreshing()
                
                //                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
        }
        
        
    }
    
    
    
    func cachePictures(){
        
        
        let grop = DispatchGroup()
        
        
        for model in homeData {
            
            if model.type == "2" {
                
                guard let urlString = model.item_data?.image else {
                    continue
                }
                
                grop.enter()
                
                SDWebImageManager.shared().downloadImage(with: URL(string: urlString), options: [], progress: nil, completed: { (_, _, _, _, _) in
                    
                    
                    grop.leave()
                    
                })
                
            }
            
        }
        
        grop.notify(queue: DispatchQueue.main) {
            
            
            
            
            self.groupTableView.mj_header.endRefreshing()
            
            self.groupTableView.reloadData()
            
            
        }
        
        
        
    }
    
}



// MARK:- tableview代理方法
extension NewCityHomeVC{
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        if HomeGloabeModel.golableModel == nil {
            return 0
        }

        if haveAD == true {
            return 3
        } else {
            return 2
        }

        
        
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if HomeGloabeModel.golableModel == nil {
            return 0
        }
        
        if section == 0 {
            
            if haveSrollImage == true {
                return 2
            } else {
                return 1
            }
            
            
        } else {
            
            return 1

            
        }
        
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var tableCell : UITableViewCell? = nil
        
        if indexPath.section == 0 {
            if haveSrollImage == true {
                
                if indexPath.row == 0 {
                    
                    let tempCell : HomeTopCell =  tableView.dequeueReusableCell(withIdentifier: HomeTopCell.identifer()) as! HomeTopCell
                    
                    tempCell.items =  homeData[0].item_data?.item
                    
                    tableCell = tempCell
                    
                } else {
                    
                    tableCell =  tableView.dequeueReusableCell(withIdentifier: NewCityProgramaCell.identifer())
                    
                }
                
            } else {
                
                tableCell =  tableView.dequeueReusableCell(withIdentifier: NewCityProgramaCell.identifer())
                
            }
            
            
        } else {
            
            if indexPath.section == 1 {
//                QL1(haveAD)

                if haveAD == true {
                    
//                    QL1(haveAD)
                    
                    let tempCell : HomeADTableCell  =  tableView.dequeueReusableCell(withIdentifier: HomeADTableCell.identifer()) as! HomeADTableCell
                    
                    tempCell.model = ADModel
                    
                    tableCell = tempCell

                    
                } else {
//                    QL1(haveAD)

                    let tempCell : HomeFeatureCell =  tableView.dequeueReusableCell(withIdentifier: HomeFeatureCell.identifer()) as! HomeFeatureCell
                    
                    tempCell.isNewCity = true
                    
                    
                    tableCell = tempCell

                    
                }
                
            } else {
                
                let tempCell : HomeFeatureCell =  tableView.dequeueReusableCell(withIdentifier: HomeFeatureCell.identifer()) as! HomeFeatureCell
                
                tempCell.isNewCity = true
                
                
                tableCell = tempCell

                
            }
            
            
            
            
            
            
            
        }
        
        
        return tableCell!
    }
    
    
    
    
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        
        if section == 0 {
            return 0.00001
        } else {
            
            if section == 1 {
                
                if haveAD == true{
                    
                    return 0.00001

                
                }else{
                
                    return 36

                
                }

            } else {
                
                return 36

            }
        }
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        return 0.00001
        
    }
    
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if section == 0 {
            return UIView()
        } else {
            if section == 1 {
        
                if haveAD == true {
                    
                    return UIView()

                } else {
                    
                    let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: HomeSetionHeader.identifer()) as! HomeSetionHeader
                    
                    view.title = "特色频道"
                    
                    return view
                }
                
                
            } else {
                
                let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: HomeSetionHeader.identifer()) as! HomeSetionHeader
                
                view.title = "特色频道"

                
                return view
            }
        }
        

        
 
    }
    
    
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        //        super.tableView(tableView, didSelectRowAt: indexPath)
        
    }
    
    
    
}

